﻿using System;
using System.Drawing;
using System.Windows.Forms;
using log4net.Appender;
using log4net.Core;

namespace FreeBitExcel.service
{
    public class LogReader : AppenderSkeleton
    {
        private ListBox m_ListBox;
        public string FormName { get; set; }
        public string ListBoxName { get; set; }
        protected override void Append(LoggingEvent loggingEvent)
        {
            if (m_ListBox == null)
            {
                if (String.IsNullOrEmpty(FormName) ||
                    String.IsNullOrEmpty(ListBoxName))
                    return;
                Form form = Application.OpenForms[FormName];
                if (form == null)
                    return;
                m_ListBox = FindControlRecursive(form, ListBoxName) as ListBox;
                if (m_ListBox == null)
                    return;
                m_ListBox.BeginInvoke((MethodInvoker)delegate
                {
                    m_ListBox.DrawMode = DrawMode.OwnerDrawFixed;
                });
                m_ListBox.DrawItem += new DrawItemEventHandler(m_ListBox_DrawItem);
                form.FormClosing += (s, e) => m_ListBox = null;
            }
            m_ListBox.BeginInvoke((MethodInvoker) delegate
            {
                if (loggingEvent.Level >= Level.Warn)
                {
                    m_ListBox.Items.Add("red_" + RenderLoggingEvent(loggingEvent));
                }
                else
                {
                    m_ListBox.Items.Add(RenderLoggingEvent(loggingEvent));
                }
                this.m_ListBox.TopIndex = this.m_ListBox.Items.Count - (int)(this.m_ListBox.Height / this.m_ListBox.ItemHeight);

            });
        }
        void m_ListBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            Brush FontBrush = null;
            ListBox listBox = sender as ListBox;
            if (e.Index > -1)
            {
                string str = listBox.Items[e.Index].ToString();
                if (str.StartsWith("red_"))
                {
                    FontBrush = Brushes.Red;
                    str = str.Replace("red_", "");
                }
                else
                {
                    FontBrush = Brushes.Black;
                }
                e.DrawBackground();
                e.Graphics.DrawString(str, e.Font, FontBrush, e.Bounds);
                e.DrawFocusRectangle();
            }
        }
        private Control FindControlRecursive(Control root, string ControlName)
        {
            if (root.Name == ControlName) return root;
            foreach (Control c in root.Controls)
            {
                Control t = FindControlRecursive(c, ControlName);
                if (t != null) return t;
            }
            return null;
        }
    }
}